package com.lwm.annotationandreflection.ref;

import com.lwm.entity.Employee;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author liweimin
 * @date 2020/9/25 14:12
 * @description 性能分析
 */
public class ref09 {


    public static void test01() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //普通方式调用
        Employee employee = new Employee();
        long l = System.currentTimeMillis();
        for (int i = 0; i < 1000_000_00; i++) {
            employee.getName();
        }
        long l1 = System.currentTimeMillis();
        System.out.println("普通方式执行时间为：" + (l1 - l) + "ms");
    }

    public static void test02() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //反射调用
        Class clazz = Class.forName("com.lwm.entity.Employee");
        Employee employee1 = (Employee) clazz.newInstance();
        long start = System.currentTimeMillis();
        Method getName = clazz.getDeclaredMethod("getName", null);
        for (int i = 0; i < 1000_000_00; i++) {
            getName.invoke(employee1, null);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射方式执行时间为：" + (end - start) + "ms");
    }

    public static void test03() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        //反射调用关闭检测
        Class clazz = Class.forName("com.lwm.entity.Employee");
        Employee employee1 = (Employee) clazz.newInstance();
        long start = System.currentTimeMillis();
        Method getName = clazz.getDeclaredMethod("getName", null);
        getName.setAccessible(true);
        for (int i = 0; i < 1000_000_00; i++) {
            getName.invoke(employee1, null);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射方式(关闭检测)执行时间为：" + (end - start) + "ms");
    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        test01();
        test02();
        test03();
    }
}

